<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Goods;
use app\common\model\PrizeDraw;
use think\Cache;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 首页接口
 */
class Prize extends Api
{
    protected $noNeedLogin = ['toHtml','index'];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = new \app\common\model\Prize;
    }

    /**
     * 获取 抽奖列表
     *
     */
    public function index()
    {
        $map = [
            'switch' => 1
        ];

        $where = [
            'user_id' => $this->auth->id,
            //'fa_prize_draw.opentime' => ['on','fa_prize.opentime']
        ];

        //显示10条分页数据
        $data = $this->model
            ->with(['goods'=>function($query){
                $query->field('id,name,price');
            }])
            ->field("id,name,image,goods_id,price,total,num, from_unixtime(starttime,'%m-%d %H:%i') as starttime, from_unixtime(endtime,'%m-%d %H:%i') as endtime, from_unixtime(opentime,'%m-%d %H:%i') as opentime,opentime as opentimestamp,weigh")
            ->with(['prizedraw'=>function($query)use($where){
                $query->where($where)->field('id,prize_id,opentime');
            }])
            ->where($map)
            ->order('top_switch desc,weigh asc')
            ->paginate(10);

        $data = addWebSiteUrl($data, ['image']);

        //抽奖列表 返回用户是否报名抽奖的状态 0 1 抽奖记录和抽奖列表关联获取
        //暂时设置缓存 先返回状态

        foreach($data as $k=>$v){
            //Cache::tag('')->get();
            $is_draw = 0;
            if ($v['prizedraw']){
                $opentimeArr = array_column($v['prizedraw'],'opentime');
                $is_draw = in_array($v['opentimestamp'],$opentimeArr) ? 1 : 0;
            }
            $data[$k]['is_draw'] = $is_draw; //用户是否报名
            unset($v['prizedraw']);
        }

        $this->success('i18n:62',$data);
    }

    /**
     * 抽奖列表详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $id = $this->request->request('id');
        $map = [];

        $data = $this->model
            ->with(['goods'=>function($query){
                $query->field('id,name,price,brief,image,images,intro_content,spes_desc,params')
                ->with(['products'=>function($query2){
                    $query2->field('id,goods_id,price,is_defalut,image,sn,stock,spes_desc');
                }]);
            }])
            ->field("id,name,image,goods_id,price,total,num,starttime,endtime,opentime")
            ->where($map)
            ->find($id);

        if (!$data){
            $this->error('i18n:172');
        }

        //图片相对地址转绝对地址 begin

        if ($data['image']) {
            $data['image'] = getRealUrl($data['image']);
        }

        if ($data['goods']['image']) {
            $data['goods']['image'] = getRealUrl($data['goods']['image']);
        }

        if ($data['goods']['images']) {
            $images = explode(',',$data['goods']['images']);
            foreach ($images as $k =>$v){
                $images[$k] = getRealUrl($v);
            }
            $data['goods']['images'] = $images;
        }

        //编辑框图片转绝对地址
        $intro_images = [];
        if (isset($data['goods']['intro_content'])) {
            preg_match_all('/(?<=img.src=").*?(?=")/', $data['goods']['intro_content'], $out, PREG_PATTERN_ORDER);      //正则匹配img标签的src属性，返回二维数组
            if (!empty($out)) {
                foreach ($out as $v) {
                    foreach ($v as $j) {
                        $url = getRealUrl($j);
                        $intro_images[] = $url;
                        $data['goods']['intro_content'] = str_replace($j, $url, $data['goods']['intro_content']);   //替换相对路径为绝对路径
                    }
                }
            }
        }
        $data['goods']['intro_images'] = $intro_images;
        //图片处理 end

        //获取抽奖报名总人数

        //获取抽奖记录model
        $prizeDrawModel = new PrizeDraw();
        $where = [
            'opentime' => $data['opentime'],
            'prize_id' => $data['id'],
        ];
        //查询报名抽奖总人数
        $join_total = $prizeDrawModel->where($where)->count();

        //用户是否报名
        //获取用户信息
        $userInfo = $this->auth->getUserinfo();
        $where['user_id'] = $userInfo['id'];
        //增加user_id 条件，查询该用户是否已报名
        $is_draw = $prizeDrawModel->where($where)->count();

        //TODO 抽奖详情 用户是否报名 已抽奖人数
        $data['is_draw'] = ($is_draw) ? 1 : 0;
        $data['join_total'] = $join_total + 100;

        //倒计时用时间戳
        $data['countdown'] = $data['opentime'];
        //处理时间戳
        $data['starttime'] = date('m-d H:i',$data['starttime']);
        $data['endtime'] = date('m-d H:i',$data['endtime']);
        $data['opentime'] = date('m-d H:i',$data['opentime']);

        $request = Request::instance();
        $domain = $request->domain();
        $data['goods']['intro_html'] = $domain . '/api/prize/toHtml?gid='.$data['goods_id'];

        //多规格参数
        //$data['goods']['spes_desc'] = unserialize($data['goods']['spes_desc']);
        $params = unserialize($data['goods']['params']);
        if (is_array($params)){
            foreach($params as $k=>$v){
                if (is_array($v)){
                    $params[$k] = implode('|',$v);
                }
            }
        }
        $data['goods']['params'] = $params;

        $this->success('i18n:62',$data);
    }


    /**
     * 商品内容详情 返回html
     * @return string|string[]|\think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function toHtml(){

        //获取商品id
        $goodsid = $this->request->request('gid');

        if (!$goodsid) {
            return redirect('/404.html');
        }

        $goodsModel = new Goods();
        $data = $goodsModel->where(['deletetime'=>null])->find($goodsid);

        if (!$data) {
            return redirect('/404.html');
        }

        $html = '';
        //编辑框图片转绝对地址
        if (isset($data['intro_content'])) {
            preg_match_all('/(?<=img.src=").*?(?=")/', $data['intro_content'], $out, PREG_PATTERN_ORDER);      //正则匹配img标签的src属性，返回二维数组
            if (!empty($out)) {
                foreach ($out as $v) {
                    foreach ($v as $j) {
                        $url = getRealUrl($j);
                        $html = str_replace($j, $url, $data['intro_content']);   //替换相对路径为绝对路径
                    }
                }
            }
        }

        return $html;
    }

    /**
     * 单个抽奖报名
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function draw(){
        $id = $this->request->request('id');

        //获取用户信息
        $userInfo = $this->auth->getUserinfo();

        //获取抽奖记录model
        $prizeDrawModel = new PrizeDraw();

        //搜索条件
        $map = [
            'switch' => 1, //抽奖开启
        ];
        //获取抽奖信息

        $prizeInfo = $this->model
            ->with(['goods'=>function($query){
                $query->field('id,name,price,brief,image,images,intro_content');
            }])
            ->field("id,name,image,goods_id,price,total,num,starttime, endtime,opentime,is_member")
            ->where($map)
            ->find($id);

        if (!$prizeInfo) $this->error('i18n:171');

        //判断是否符合报名时间
        if ($prizeInfo['starttime'] > time()) {
			$this->error('i18n:170');
		}

        if ($prizeInfo['endtime'] < time()) {
			$this->error('i18n:169');
		}

        //判断是否已经报名抽奖
        $where = [
            'opentime' => $prizeInfo['opentime'],
            'prize_id' => $prizeInfo['id'],
            'user_id'  => $userInfo['id'],
        ];
        $prizeDraw = $prizeDrawModel->where($where)->select();
        if ($prizeDraw) $this->error('i18n:168');

        //判断抽奖资格 判断是否已报名抽奖 增加抽奖记录
        if ($prizeInfo['is_member'] == 1 && $userInfo['is_member'] == 0) $this->error('i18n:167');

        //抽奖记录 数据
        $params = [
            'prize_id'  => $prizeInfo['id'],
            'user_id'   => $userInfo['id'],
            'opentime'  => $prizeInfo['opentime'], //开奖时间戳
            'goods_id'  => $prizeInfo['goods_id'], //商品id
            'price'     => $prizeInfo['price'], //价格
            'num'       => $prizeInfo['num'], //数量
            'is_opened' => 0, //是否开奖
        ];
        /*echo '<pre>';
        var_dump($params);exit;*/

        $result = $prizeDrawModel->save($params);

        if (!$result) $this->error('i18n:166');



        $this->success('i18n:165',['id'=>$prizeInfo['id']]);
    }

    /**
     * 一键抽奖报名
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function drawAll(){

        //获取用户信息
        $userInfo = $this->auth->getUserinfo();

        //获取抽奖记录model
        $prizeDrawModel = new PrizeDraw();

        //也可以增加会员限制，只允许会员用户可以一键抽奖报名，提示成为会员

        $nowTime = time();
        //获取可以一键抽奖报名的抽奖列表
        $map = [
            'starttime' => ['<',$nowTime],
            'endtime'   => ['>',$nowTime],
            'switch'    => 1,
            'd.id'      => null
        ];

        //如果用户不是会员，增加抽奖is_member 条件 为 0
        if (!$userInfo['is_member']) $map['is_member'] = 0;

        //获取用户可报名的抽奖
        $prizelist = $this->model
            ->with(['goods'=>function($query){
                $query->field('id,name,price,brief,image,images,intro_content');
            }])
            ->alias('p')
            //关联fa_prize_draw on prize_id onentime user_id
            ->join('fa_prize_draw d','p.id=d.prize_id and p.opentime=d.opentime and d.user_id='.$userInfo['id'],'LEFT')
            ->field("p.id,p.name,p.image,p.goods_id,p.price,p.total,p.num,p.starttime,p.endtime,p.opentime,p.is_member,d.id as drawid")
            ->where($map)
            ->select();

        if (!$prizelist)  $this->error('i18n:164');

        $params = [];
        //整理批量添加数据
        foreach ($prizelist as $k=>$v){
            $param = [
                'prize_id'  => $v['id'],
                'user_id'   => $userInfo['id'],
                'opentime'  => $v['opentime'], //开奖时间戳
                'goods_id'  => $v['goods_id'], //商品id
                'price'     => $v['price'], //价格
                'num'       => $v['num'], //数量
                'is_opened' => 0, //是否开奖
            ];
            $params[] = $param;
        }

        if ($params){
            $result = $prizeDrawModel->saveAll($params);
            if (!$result) $this->error('i18n:163');
        }

        //$msg = '恭喜您！一键报名成功,数量：' . count($result) . '个';
		$msg = 'i18n:162';

        $this->success($msg,['ids' => array_column($result,'id')]);
    }


    /**
     * 领奖信息管理 获取列表
     * @throws \think\exception\DbException
     */
    public function winList(){

        //获取tab状态 all全部 shipped已发货 noprize未领奖 giveup已弃奖
        $status = $this->request->request('status');
        $prizeDrawModel = new PrizeDraw();

        $map = [
            'is_opened' => 1,
            'is_win'    => 1,
            'p.user_id'   => $this->auth->id,
        ];

        switch ($status){
            case 'noprize':
                //未领奖
                $map['status'] = 0;
                break;
            case 'shipped':
                //已领货
                $map['status'] = 1;
                //已发货
                //$map['d.state'] = 1;
                break;
            case 'giveup':
                //已弃奖
                $map['status'] = 2;
                break;
            default:
                break;

        }

        $data = $prizeDrawModel
            ->with(['goods'=>function($query){
                $query->field('id,name,price,image');
            }])
            ->alias('p')
            ->join('fa_order d','d.order_sn=p.order_sn','LEFT')
            ->field('p.id,p.prize_id,p.user_id,p.opentime,p.goods_id,p.price,p.num,p.status,p.order_sn,d.state as order_state')
            ->where($map)
            ->paginate(10);

        //TODO
        //with 查询关联表内的字段 关联设置 setEagerlyType = 0 join 如果多级嵌套关联 需去掉setEagerlyType() 否则只显示一级
        //with + alias 别名无效 需要 join
        //主表增加with内字段作为查询条件 with方法名.字段 如 order.state,主表字段 需要加上主表全名前缀 如 fa_prize_draw.id
        //with内查询条件，过滤with方法中的 内容
        /*$data = $prizeDrawModel
            ->with(['goods'=>function($query){
                $query->field('id,name,price');
            }])
            ->with('order')
            ->field('fa_prize_draw.id,fa_prize_draw.prize_id,fa_prize_draw.user_id,fa_prize_draw.opentime,fa_prize_draw.goods_id,fa_prize_draw.price,fa_prize_draw.num,fa_prize_draw.status,fa_prize_draw.order_sn,order.state')
            ->where($map)
            ->paginate(10);*/

        $statusDict = [
            0 => 'i18n:11',
            1 => 'i18n:161',
            2 => 'i18n:51',
        ];

        //处理data
        foreach ($data as $k=>$v){
            $data[$k]['goods']['image'] = getRealUrl($v['goods']['image']);

            //返回领奖信息
            $tips = '';
            if ($v['status'] == 1){
                if (!$v['order_sn']) $tips = $statusDict[$v['status']];
            }else{
                $tips = isset($statusDict[$v['status']]) ? $statusDict[$v['status']] : '';
            }

            $data[$k]['tips']  = $tips;
        }

        $this->success('i18n:62',$data);
    }

}
